package org.yysd.example;

import okhttp3.*;

import java.io.IOException;

public class OkHttpExample {
    private static final OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws IOException {
        // 发送GET请求（带参数）
        sendGetRequestWithParams("https://api.example.com/users", "id", "123");

        // 发送POST请求
        sendPostRequest("https://api.example.com/users", "{\"name\":\"John\", \"age\":30}");

        // 发送PUT请求
        sendPutRequest("https://api.example.com/users/123", "{\"name\":\"John Doe\", \"age\":35}");

        // 发送DELETE请求
        sendDeleteRequest("https://api.example.com/users/123");
    }

    // 发送GET请求（带参数）
    private static void sendGetRequestWithParams(String url, String paramName, String paramValue) throws IOException {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        urlBuilder.addQueryParameter(paramName, paramValue);
        String requestUrl = urlBuilder.build().toString();

        Request request = new Request.Builder()
                .url(requestUrl)
                .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }

    // 发送POST请求
    private static void sendPostRequest(String url, String jsonBody) throws IOException {
        RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json"));

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }

    // 发送PUT请求
    private static void sendPutRequest(String url, String jsonBody) throws IOException {
        RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json"));

        Request request = new Request.Builder()
                .url(url)
                .put(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }

    // 发送DELETE请求
    private static void sendDeleteRequest(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .delete()
                .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }
}
